package com.bulletelc.apollopre.module.main.center.orders.fragment;

import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.OrderDetailBean;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.MyUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * author: lhl
 * date  : 2018/2/3
 * desc  : TODO
 */

public class OrderStatePresenter extends BasePresenter<OrderStateContract.View> implements OrderStateContract.Presenter {
    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void getOrderList(int page) {
        getOrderListImp(null,page);
    }

    @Override
    public void getOrderList(String json,int page) {
        getOrderListImp(json,page);
    }

    @Override
    public void cancelOrder(String json) {
        cancelOrderImp(json);
    }

    /**
     * 获取订单列表
     * @param json
     */
    private void getOrderListImp(String json,int page) {
        PostRequest<String> postRequest = OkGo.<String>post(NetWorkPath.POST_ORDER_LIST + "?page=" + page)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken());
        if (json!=null) {
            RequestBody body=RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON),json);
            postRequest.upRequestBody(body);
        }
        postRequest.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                parseOrderList(response);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                if (isViewAttached()) {
                    getView().onError(response.getException().toString());
                }
            }
        });


    }

    /**
     *
     */
    private void parseOrderList(Response<String> response){
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(metaObj.getString("code"))) {
                    JSONObject extraData=metaObj.getJSONObject("extraData");
                    int pageCount = extraData.getInt("pageCount");
                    Gson gson = new Gson();
                    Type typeGson = new TypeToken<List<OrderDetailBean>>() {
                    }.getType();
                    List<OrderDetailBean> orderDetailBeans = gson.fromJson(object.getJSONArray("data").toString(),typeGson);
                    if (isViewAttached()) {
                        getView().onSuccess(orderDetailBeans,pageCount);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFail(metaObj.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onError("数据解析有误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFail(response.body().toString());
            }
        }
    }

    /**
     * 取消订单
     *
     * @param json
     */
    private void cancelOrderImp(String json) {
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_ORDER_STATE_UPDATE)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken())
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //LogUtil.i(response.body().toString());
                        parseCancelOrder(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorCancelOrder(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析取消订单返回的数据
     *
     * @param response
     */
    private void parseCancelOrder(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(metaObj.getString("code"))) {
                    if (isViewAttached()) {
                        getView().onSuccessCancelOrder();
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailCancelOrder(metaObj.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorCancelOrder("数据解析有误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailCancelOrder(response.body().toString());
            }
        }
    }
}
